// main.c - IR test main function
//

#include "system.h"

_CONFIG1( JTAGEN_OFF & GCP_OFF & GWRP_OFF & BKBUG_OFF & COE_OFF & ICS_PGx1 & FWDTEN_OFF & WINDIS_OFF & FWPSA_PR32 & WDTPS_PS1) 
_CONFIG2( IESO_OFF & SOSCSEL_SOSC & WUPTSEL_LPSOSC & FNOSC_FRC & FCKSM_CSDCMD & OSCIOFNC_OFF & IOL1WAY_OFF & I2C1SEL_PRI & POSCMOD_NONE)

extern INTERRUPTHANDLERS interrupts;

byte inByte;
int packetLength;
comPacket inPacket, outPacket;
byte data[MaxPacketLength-6];
byte sendArray[MaxPacketLength];


extern int rfidDataAvailable;
extern byte rfidTag[12];
extern SignalState signalState;

int main(void)
{

	byte emptyRfidTag[12] = {0,0,0,0,0,0,0,0,0,0,0,0};

	initPins();
	initInterrupts();
	initTimer();
	initUart();
	initUart2();

	RFIDEN = 0;	//Enable RFID Chip

	LED1 = 1;
	LED2 = 1;
	LED3 = 1;
	LED4 = 1;
	
	RS485RE_n = 0;
	RS485DE = 0;

	initIrSensors(!IR1I || !IR2I);

	sendStartup(0, "", 0);

	while(1)
	{
		//LED1 = 0;
		switch (checkIrSensors(data))
		{
			case IDLE:
				LED4 = 1;
				switch (signalState)
				{
					case RED:
						LED1 = 0;
						LED2 = 1;
						LED3 = 1;
						break;
					case GREEN:
						LED1 = 1;
						LED2 = 0;
						LED3 = 1;
						break;
					case YELLOW:
						LED1 = 1;
						LED2 = 1;
						LED3 = 0;
						break;
					default:
						LED1 = 1;
						LED2 = 1;
						LED3 = 1;
						break;
				}
				break;
			case WAITFORIR2:
			case WAITFORIR1:
				LED4 = 0;
				break;
			case LOGTIME:
				LED1 = 1;
				LED2 = 1;
				LED3 = 0;
				LED4 = 1;
				//Check for RFID Data
				if(rfidDataAvailable)	//RFID data available
				{
					sendCMDFront(rfidTag,data);
					rfidDataAvailable = 0;
					LED2=1;
				}
				else 	//No RFID data available
				{
					sendCMDFront(emptyRfidTag,data);
				}
					
				break;
			case LOGTIMEEND:
				LED1 = 1;
				LED2 = 1;
				LED3 = 1;
				LED4 = 1;
				//Check for RFID Data
				if(rfidDataAvailable)	//RFID data available
				{
					sendCMDBack(rfidTag,data);
					rfidDataAvailable = 0;
					LED2=1;
				}
				else 	//No RFID data available
				{
					sendCMDBack(emptyRfidTag,data);
				}
					
				break;				
			case PASSING:
				break;
			default:
				break;
		}

		if(receiveChar((char *)(&inByte)))
		{
			store_DataIn(inByte);	//Store the byte into a packet
		}
		
	}

	return 0;
}

